<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" inline>
      <el-form-item prop="invoiceDate">
        <el-date-picker
          v-model="queryParams.invoiceDate"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="开票日期"
        />
      </el-form-item>
      <el-form-item prop="feesType">
        <el-select v-model="queryParams.feesType" placeholder="发票类型">
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="订单所属人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="invoiceHandlingPersonnel">
        <el-select
          v-model="queryParams.invoiceHandlingPersonnel"
          placeholder="发票经手人员"
        >
          <el-option
            v-for="item in billToPersonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-radio-group
      v-model="queryParams.invoiceStatus"
      size="mini"
      class="invoiceStatus"
      @input="getList"
    >
      <el-radio-button :label="null">全部</el-radio-button>
      <el-radio-button :label="2">已开票</el-radio-button>
      <el-radio-button :label="1">未开票</el-radio-button>
    </el-radio-group>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:detail:add']"
        >
          添加
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" border :data="dataList">
      <el-table-column label="发票编号" align="center" prop="invoiceManagementId" />
      <el-table-column label="关联订单" align="center" prop="orderItemSn" />
      <el-table-column label="开票日期" align="center" prop="invoiceDate" />
      <el-table-column label="发票类型" align="center" prop="feesType">
        <template slot-scope="scope">
          <span>{{ scope.row.feesType | ctFeesType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开票金额" align="center" prop="amount" />
      <el-table-column label="发票号码" align="center" prop="invoiceNumber" />
      <el-table-column label="发票内容 " align="center" prop="invoiceContent" />
      <el-table-column label="订单所属人员" align="center" prop="nickName" />
      <el-table-column label="发票经手人员" align="center">
        <template slot-scope="scope">
          {{ getHandName(scope.row.invoiceHandlingPersonnel) }}
        </template>
      </el-table-column>
      <el-table-column label="发票状态" align="center" prop="invoiceStatus">
        <template slot-scope="scope">
          <span>{{ scope.row.invoiceStatus | cInvoiceStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:detail:edit']"
            v-if="scope.row.invoiceStatus == 1"
          >
            开票
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:detail:edit']"
          >
            详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:detail:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.params.pageNum"
      :limit.sync="queryParams.params.pageSize"
      @pagination="getList"
    />

    <el-dialog title="发票详情" :visible.sync="detailShow" width="500px" append-to-body :close-on-click-modal="false">
      <el-descriptions
        class="margin-top"
        title="基本信息"
        :column="1"
        border
        :label-style="{ width: '120px', textAlign: 'center' }"
      >
        <el-descriptions-item label="开票日期">
          {{ detailRow.invoiceDate }}
        </el-descriptions-item>
        <el-descriptions-item label="开票金额">
          {{ detailRow.amount }}
        </el-descriptions-item>
        <el-descriptions-item label="关联客户">
          {{ getNickName(detailRow.userId) }}
        </el-descriptions-item>
        <el-descriptions-item label="关联订单">
          {{ detailRow.orderItemSn }}
        </el-descriptions-item>
        <el-descriptions-item label="发票类型">
          {{ detailRow.feesType | ctFeesType  }}
        </el-descriptions-item>

        <el-descriptions-item label="纳税人识别号">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.taxpayerId : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="收件人姓名">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.recipientName : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="收件人地址">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.recipientAddress : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="邮政编码">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.zipCode : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系邮箱">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.email : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ detailRow.sysUserInvoiceInformation ? detailRow.sysUserInvoiceInformation.phoneNumber : '-' }}
        </el-descriptions-item>

        <el-descriptions-item label="发票内容">
          {{ detailRow.invoiceContent }}
        </el-descriptions-item>
        <el-descriptions-item label="发票号码">
          {{ detailRow.invoiceNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="发票经手人员">
          {{ getHandName(detailRow.invoiceHandlingPersonnel) }}
        </el-descriptions-item>
        <el-descriptions-item label="附件">
          <el-image
            style="width: 100px; height: 100px"
            :src="srcList[0]"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="srcList"
            :initial-index="4"
            fit="cover"
            v-if="srcList.length"
          />
          <div v-if="pdfList.length">
            <a :href="pdf" style="color: blue;margin-bottom: 20px;display: inline-block;" v-for="pdf in pdfList" :key="pdf">{{  getName(pdf) }}</a>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions
        class="margin-top"
        title="系统信息"
        :column="1"
        border
        :label-style="{ width: '120px', textAlign: 'center' }"
      >
        <el-descriptions-item label="创建时间">
          {{ detailRow.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ detailRow.updateTime }}
        </el-descriptions-item>
      </el-descriptions>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailCancel">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="form.invoiceManagementId ? '修改开票' : '新增开票'"
      :visible.sync="editShow"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="flex">
          <div>
            <el-form-item label="关联客户" v-if="!form.invoiceManagementId" prop="userId">
              <el-select
                v-model="form.userId"
                filterable
                placeholder="选择客户"
                @change="queryOrder"
              >
                <el-option
                  v-for="item in personList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单编号" prop="orderItemId">
              <el-select
                v-model="form.orderItemId"
                multiple
                :disabled="form.invoiceManagementId? true : false"
                placeholder="请选择订单编号"
                @change="changePrice"
              >
                <el-option
                  v-for="item in orderList"
                  :key="item.orderItemId"
                  :label="item.sn"
                  :value="item.orderItemId"
                >
                  <span>{{ item.sn }}</span>
                  <span style="color: #c0c0c0">({{ item.updatePrice || 0 }}元)</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="form.invoiceDate"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="订单类型" v-if="!form.invoiceManagementId" prop="type">
              <el-select v-model="form.type" placeholder="选择类型" @change="queryOrder">
                <el-option
                  v-for="item in orderTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="开票金额" prop="amount">
              <el-input placeholder="选择订单后自动计算" v-model="form.amount" disabled>
                <template slot="append" style="color: #fff">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="发票类型" prop="feesType">
              <el-select v-model="form.feesType" placeholder="选择类型">
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="发票内容" prop="invoiceContent">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入发票内容"
            v-model="form.invoiceContent"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="fileUrl">
          <File-upload
            v-model="form.fileUrl"
            :fileType="['pdf', 'png', 'jpg', 'jpeg']"
            label="点击上传发票附件"
            :isShowTip="true"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="invoicingCancel">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBill,
  delBill,
  updateBill,
  addBill,
  billManager,
} from "@/api/financialManagement/billManagement";
import { listOrder, getMemberList } from "@/api/financialManagement/orderManagement";

export default {
  data() {
    return {
      srcList:[],//图片列表
      pdfList:[],//pdf列表
      baseUrl: process.env.VUE_APP_BASE_API,
      fileList: [], //上传文件数组
      detailRow: [], //发票详情数据
      billToPersonList: [], //发票经手人员
      personList: [], // 关联客户
      //发票类型列表
      typeList: [
        { value: "1", label: "增值税普通发票" },
        { value: "2", label: "增值税专用发票" },
      ],
      //订单类型列表
      orderTypeList: [
        { value: "CLOUD_SERVER", label: "云服务器" },
        { value: "CLOUD_MARKET", label: "云市场" },
        { value: "GOV_CLOUD", label: "政务云" },
        { value: "CLOUD_SERVER_RENEW", label: "云服务器续费" },
        { value: "CLOUD_SERVER_CHANGE", label: "云服务器变更" },
      ],
      orderList: [], // 订单列表
      loading: false, // 遮罩层
      total: 0, // 总条数
      dataList: [], // 数据列表
      detailShow: false, // 详情弹出层
      editShow: false, //开票对话框
      // 查询参数
      queryParams: {
        feesType: null, //发票类型
        nickName: null, //订单所属人员
        invoiceHandlingPersonnel: null, //发票经手人员
        invoiceDate: null, //开票日期
        invoiceStatus: null, //发票状态
        params: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      form: {}, // 表单参数
      // 表单校验
      rules: {
        userId: [{ required: true, message: "请输入关联客户", trigger: "blur" }],
        orderItemId: [{ required: true, message: "请选择订单编号", trigger: "blur" }],
        invoiceDate: [{ required: true, message: "请选择日期", trigger: "blur" }],
        feesType: [{ required: true, message: "请选择发票类型", trigger: "blur" }],
        invoiceNumber: [{ required: true, message: "请输入发票号码", trigger: "blur" }],
        invoiceContent: [{ required: true, message: "请输入发票内容", trigger: "blur" }],
        type: [{ required: true, message: "请选择订单类型", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getMember();
    this.getList();
    this.getBillManager();
  },
  methods: {
    //截取文件名字
    getName(pdf) {
      const arr = pdf.split('/');
      const nameArr = arr[arr.length - 1]?.split('_');
      return nameArr[0]
    },
    /**获取发票经手人员的列表，渲染下拉框选项 */
    getBillManager() {
      billManager().then((res) => {
        if (200 === res.code) {
          res.data.forEach((item) => {
            this.billToPersonList.push({
              value: item.userId,
              label: item.nickName,
            });
          });
        }
      });
    },
    // 获取客户列表
    getMember() {
      getMemberList().then((res) => {
        this.personList = res.data;
      });
    },
    /**关闭开票对话框 */
    invoicingCancel() {
      this.editShow = false;
      this.reset();
    },
    // 获取关联客户名称
    getNickName(val) {
      let row = this.personList.find((i) => i.userId == val);
      return row ? row.nickName : "";
    },
    // 获取经手人名称
    getHandName(val) {
      let row = this.billToPersonList.find((i) => i.value == val);
      return row ? row.label : "";
    },
    /** 查询发票列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 查询客户订单
    queryOrder() {
      const { userId, type } = this.form;
      if (userId && type) {
        let data = {
          userId,
          invoicing: 2,
          type, //按月统计下拉框的值
          orderStatus:'SUCCESS',
          params: {
            pageNum: 1,
            pageSize: 1000,
          },
        };
        listOrder(data).then((res) => {
          this.orderList = res.rows;
        });
      } else {
        this.orderList = [];
      }
    },
    // 取消按钮
    detailCancel() {
      this.detailShow = false;
    },
    // 计算价格
    changePrice(e) {
      let amount = 0;
      e.forEach((item) => {
        let row = this.orderList.find((i) => i.orderItemId == item);
        if (row) {
          amount += row.updatePrice;
        }
      });
      this.form.amount = amount;
    },
    // 表单重置
    reset() {
      this.form = {
        invoiceManagementId: null,
        userId: null,
        orderItemId: null,
        amount: null,
        feesType: null,
        invoiceDate: null,
        fileUrl: null,
        invoiceNumber: null,
        invoiceContent: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.editShow = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = Object.assign({}, row);
      this.form.orderItemId = row.orderItemId.split(",");
      this.editShow = true;
    },
    /**点击详情 */
    handleDetail(row) {
      this.srcList = [];
      this.pdfList = [];
      this.detailRow = Object.assign({}, row);
      const urlList = this.detailRow.fileUrl?.split(',').map(item =>  this.baseUrl + item);
      urlList?.forEach(item => {
        if (item.includes('.pdf')) {
          this.pdfList.push(item);
        } else {
          this.srcList.push(item);
        }
      })
      this.detailShow = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let data = Object.assign({}, this.form);
          data.orderItemId = data.orderItemId.join(",");
          if (data.invoiceManagementId) {
            updateBill(data).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.editShow = false;
              this.getList();
            });
          } else {
            addBill(data).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.editShow = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除发票订单为【" + row.orderItemId + "】的数据项？")
        .then(() => {
          delBill([row.invoiceManagementId]).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.invoiceStatus {
  margin-bottom: 20px;
}
.margin-top {
  margin-top: 20px;
}
.flex {
  display: flex;
  > div {
    flex: 1;
  }
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-select {
  width: 100%;
}
</style>
